package com.czxy.tanhua.service;

import com.czxy.tanhua.dubbo.api.UserInfoApi;
import com.czxy.tanhua.dubbo.mongoapi.CommentApi;
import com.czxy.tanhua.entity.UserInfo;
import com.czxy.tanhua.mongo.Comment;
import com.czxy.tanhua.vo.CommentTdo;
import com.czxy.tanhua.vo.CommentVo;
import com.czxy.tanhua.vo.PublicPageVo;
import com.czxy.tanhua.vo.ResultList;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 爱吃豆的土豆、
 * @Date 2023/4/12 21:46
 */
@Service
public class CommentService {
    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;
    public ResultList findComments(ObjectId movementId, PublicPageVo publicPageVo) {
        ResultList comments = commentApi.findComments(movementId, publicPageVo);
        List<Comment> items = comments.getItems();


        //传入用户APi
        Map<Long, UserInfo> userInfoMap = userInfoApi.findUserByids(items.stream().map(comment -> comment.getUserId()).collect(Collectors.toList()));

        List<CommentVo> commentVoList = new ArrayList<>();
        //处理返回数据
        for (Comment comment : items) {
            UserInfo userInfo = userInfoMap.get(comment.getUserId());
            CommentVo commentVo = new CommentVo(comment.getId().toString(),userInfo.getAvatar(),userInfo.getNickname(),comment.getContent(),
                    comment.getCreated().toString(), (int) comment.getLikeCount(),0);
            commentVoList.add(commentVo);
        }
        comments.setItems(commentVoList);
        return comments;

    }

    public void addcomment(CommentTdo commentTdo, Long userId) {
        commentApi.addcomment(commentTdo,userId);
    }
}
